from django.shortcuts import render
from django.views import View
from django import http
from .captcha.captcha import captcha
from django_redis import get_redis_connection
import json


# Create your views here.

class RegisterView( View ):
	def post(self, request):
		json_dict = json.loads( request.body.decode() )
		mobile = json_dict.get( 'mobile' )
		id = json_dict.get( 'id' )
		text = json_dict.get( 'text' )

		if not all( [mobile, id, text] ):
			return http.JsonResponse( {'erron': 4002, 'errmsg': '缺少必须数据'} )
		pass


class SmsCodeView( View ):

	def post(self, request):
		json_dict = json.loads( request.body.decode() )
		mobile = json_dict.get( 'mobile' )
		id = json_dict.get( 'id' )
		text = json_dict.get( 'text' )

		if not all( [mobile, id, text] ):
			return http.JsonResponse( {'erron': 4002, 'errmsg': '缺少必须数据'} )
		pass


class GetImageView( View ):

	def get(self, request):
		cur = request.GET.get( 'cur' )

		text, image = captcha.generate_captcha()
		redis_conn = get_redis_connection( 'image_code' )
		redis_conn.setex( 'image_%s' % cur, 300, text )

		return http.HttpResponse( image, content_type='image/jpg' )
